package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("ALL")
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        // 判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CatchCustomException.catchs(20003, "用户没有登录，不能操作");
        }
        // 判断参数
        if (wmNewsPageReqDto == null) {
            CatchCustomException.catchs(20003, "参数有误");
        }
        // 分页初始化
        wmNewsPageReqDto.checkParam();
        //封装条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 关键字
        lambdaQueryWrapper.like(
                StringUtils.isNotEmpty(wmNewsPageReqDto.getKeyword()),
                WmNews::getTitle, wmNewsPageReqDto.getKeyword()
        );
        // 频道Id
        lambdaQueryWrapper.eq(
                wmNewsPageReqDto.getChannelId() != null,
                WmNews::getChannelId, wmNewsPageReqDto.getChannelId()
        );
        // 状态
        lambdaQueryWrapper.eq(
                wmNewsPageReqDto.getStatus() != null,
                WmNews::getStatus, wmNewsPageReqDto.getStatus()
        );
        // 开始时间    createtime  >= 开始时间
        lambdaQueryWrapper.ge(
                wmNewsPageReqDto.getBeginPubDate() != null,
                WmNews::getCreatedTime, wmNewsPageReqDto.getBeginPubDate()
        );

        // 结束时间    createtime   <=  结束时间
        lambdaQueryWrapper.le(
                wmNewsPageReqDto.getEndPubDate() != null,
                WmNews::getCreatedTime, wmNewsPageReqDto.getEndPubDate()
        );
        lambdaQueryWrapper.eq(
                WmNews::getUserId, wmUser.getId()
        );
        // 写一下区间
        /* lambdaQueryWrapper.between(
                wmNewsPageReqDto.getEndPubDate()!=null && wmNewsPageReqDto.getBeginPubDate()!=null,
                WmNews::getCreatedTime,wmNewsPageReqDto.getBeginPubDate(),wmNewsPageReqDto.getEndPubDate()
        );*/
        // 排序：
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //2.分页条件查询
        IPage<WmNews> iPage = this.page(new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize()), lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(iPage.getCurrent(), iPage.getSize(), iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;
    }

    @Transactional
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            CatchCustomException.catchs(20003, "保存信息不完成，不能操作");
        }
        // 保存文章数据
        WmNews wmNews = new WmNews();
        //深克隆 -- dto 东西拿出来  --》 wmnews
        //wmNews = JSON.parseObject(JSON.toJSONString(dto),WmNews.class);
        BeanUtils.copyProperties(dto, wmNews);
        // 如果是-1 情况 代表需要从内容中获取数据 进行自定封面设置
        if (-1 == dto.getType()) {
            wmNews.setType(null);    // 目前位置 没有进行 封面自动选择  0  3  1
        }
        // 洗数据--
        // [
        //        "http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png",
        //        "http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png",
        //        "http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png"
        // ]
        // fastdfs方式
        if (dto.getImages() != null && dto.getImages().size() > 0) {
//            String images =  dto.getImages().toString()
//                    .replace("[","")
//                    .replace("]","")
//                    .replace("http://192.168.211.132:8080/","") //fastdfs方式
//                    .replace(" ","");
//            wmNews.setImages(images);
            String images = "";
            for (String image : dto.getImages()) {
                images += image + ",";
            }
            wmNews.setImages(images.substring(0, images.length() - 1));
        }
        // 保存或修改数据库
        this.saveWmNews(wmNews, isSubmit);
        // 判断类型 type  0   封面类型   0  3  1   -1

        // 获取 内容（图文内容）
        String content = dto.getContent();
        // 转换成集合  文字和图片
        List<Map> contentList = JSON.parseArray(content, Map.class);
        // 获取所有的素材（图文内容中的图片集合）
        List<String> materials = this.upGetImagesForContentList(contentList);
        // 1. 图文引用   中间表
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() != 0) {
            //设置内容
            saveRelativeInfoForNR(materials, wmNews);
        }
        // 2. 主图引用   中间表
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            // 封面与 单图 三图 无图  自动相关
            saveRelativeInfoForFM(dto, materials, wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //提取图文内容中的图片集合
    private List<String> upGetImagesForContentList(List<Map> contentList) {
        List<String> materials = new ArrayList<>();
        contentList.stream().forEach(x -> {
            if ("image".equals(x.get("type"))) {
                materials.add((String) x.get("value"));
            }
        });
        return materials;
    }

    /**
     * 设置内容图片与素材的关系
     *
     * @return
     */
    private void saveRelativeInfoForNR(List<String> materials, WmNews wmNews) {
        saveRelativeInfo(materials, wmNews, (short) 0);
    }

    /**
     * 设置封面图片与素材的关系
     *
     * @return
     */
    public void saveRelativeInfoForFM(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        // 保存关系
        // 1. 知道我有几个主图  有--》images   没有 --》图文
        List<String> imagesList = dto.getImages();
        if (-1 == dto.getType()) {  //自动
            if (materials != null && materials.size() > 0 && materials.size() <= 2) {
                // 单图
                wmNews.setType((short) 1);
                imagesList = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials != null && materials.size() > 2) {
                // 三图
                wmNews.setType((short) 3);
                imagesList = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                // 无图
                wmNews.setType((short) 0);
            }
        }
        if (imagesList != null && imagesList.size() > 0) {
            String images = "";
            for (String image : imagesList) {
                images += image + ",";
            }
            if (wmNews.getImages() == null || "".equals( wmNews.getImages())) {
                wmNews.setImages(images.substring(0, images.length() - 1));
            }
            //保存素材关系
            this.saveRelativeInfo(imagesList, wmNews, (short) 1);
        }
        // 修改wmnes
        this.updateById(wmNews);
    }

    /**
     * @param materials 素材集合
     * @param wmNews    文章信息
     * @param type      0 图文引用  1 封面引用
     * @return
     */
    private void saveRelativeInfo(List<String> materials, WmNews wmNews, Short type) {
        List<String> materialIds = new ArrayList<>();
        // 根据素材获取id
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, wmNews.getUserId());
        List<WmMaterial> list = wmMaterialMapper.selectList(lambdaQueryWrapper);
        Map<String, Integer> map = list.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        if (list != null && list.size() > 0) {
            for (String url : materials) {
                Integer materialId = map.get(url);
                materialIds.add(String.valueOf(materialId));
            }
        }
        // 保存
        wmMaterialMapper.saveRelationsByContent(materialIds, wmNews.getId(), type);
    }


    // 保存或者修改
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        // 获取用户信息
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CatchCustomException.catchs(20001, "用户米有登录");
        }
        // 草稿  或者 提交
        wmNews.setStatus(isSubmit);
        if (wmNews.getId() != null) {
            //修改
            this.updateById(wmNews);
            // 删除关联表数据   文章ID
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        } else {
            //添加
            wmNews.setUserId(wmUser.getId());
            wmNews.setCreatedTime(new Date());
            if (isSubmit == 1) {
                wmNews.setSubmitedTime(new Date());
            }
            wmNews.setEnable((short) 0);
            this.save(wmNews);
        }
    }


}
